//
//  AIDiaryReplayBean.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/11.
//
/**
 * 评论
 */
import Foundation
import SwiftUI
class AICommentRequestBean : Identifiable ,Codable {
    
    var max_tokens: Int64 = configManager.getConfig().AiConfig.maxTokens ?? 1024
    var temperature: Float64 = configManager.getConfig().AiConfig.temperature ?? 0.9
    var top_p: Float64 = configManager.getConfig().AiConfig.top_p ?? 0.95
    var stream = false
    var messages: [MessagesV2]
    var model :String
    
    
    init(model: String?,diary: DiaryBean?, list : [DiaryCommentBean], botRoleBean: RoleBean, isEnd:Bool) {
        self.model = model ?? ""
        let userRoleBean = RoleBean.get(userManager.user, botRoleBean)
        self.messages = AICommentRequestBean.getMessagesList(diary: diary, list: list, botRoleBean: botRoleBean, userRoleBean: userRoleBean, isEnd: isEnd)
    }
    
    private static func getMessagesList(diary: DiaryBean?,list : [DiaryCommentBean], botRoleBean: RoleBean,
                                        userRoleBean: RoleBean,  isEnd: Bool) ->[MessagesV2] {
        
        let time = Date().timeIntervalSince1970
        //动作描述
        let actionDescClose = !AppStorageManager.shared.toggleAiDesc ? "回复只输出最后的话语，不包括任何表情动作" : ""
        let headDesc = configManager.getConfig().getAiDescribe().headDescribe ?? ""
        let botDesc =  RoleBean.getBotDesc(botRoleBean)
        let userDesc =  RoleBean.getUserDesc(botRoleBean)
        let memoryDesc = AppStorageManager.shared.toggleMemoryInject ? configManager.getConfig().getAiDescribe().aiMemoryInjectDesc?.formatAiChatContent(ActiveAIMemoryExt.instance.getAiMemoryStr(botRoleBean: botRoleBean)) ?? "" : ""

        let ruleDesc = "\(headDesc)\(configManager.getConfig().getAiDescribe().commentDescribe ?? "")\(actionDescClose)"
        let enDesc = configManager.getConfig().getAiDescribe().enDesc ?? ""
        let desc = "\(botDesc)\n\n---\n\(userDesc)\(memoryDesc)\(enDesc)"
        
        var listMsg : [MessagesV2] = []
        listMsg.append(MessagesV2("system", botRoleBean.name ?? "", desc.formatAiChat(botRoleBean,time)))
        
        listMsg.append(MessagesV2("user", userRoleBean.name ?? "", ruleDesc.formatAiChat(botRoleBean,time)))
        
        //先添加日记内容
        if (diary != nil) {
            let roleBean = diary?.roleType == IRoleType.BOT.rawValue ? botRoleBean : userRoleBean
            listMsg.append(MessagesV2("user", roleBean.name ?? "", "这是日记内容：\(diary?.content ?? "")"))
        }
        list.forEach { it in
            if (it.role != nil) {
                let type = it.role?.isBot() == true ? "assistant" : "user"
                let name = it.role?.name ?? ""
                listMsg.append(MessagesV2(type, name, it.content ?? ""))
            }
        }
        return listMsg
    }
    
    
}
